﻿using Faser_Shop.Models.Database;
using Faser_Shop.Models.RequestModel;
using Faser_Shop.Services;
using Faser_Shop.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.Security.Claims;

namespace Faser_Shop.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class UserController : Controller
    {
        private readonly Faser_ShopContext _db;
        private readonly IJWTService _jwtService;

        public UserController(Faser_ShopContext db, IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public object Register([FromBody] UserRegisterRM model)
        {
            var hasUser = _db.Users.Any(u => u.PhoneNumber == model.PhoneNumber);
            if (hasUser)
            {
                return ApiResult.ModelValidationFailed("手机号已被注册", null);
            }

            _db.Users.Add(new User
            {
                PhoneNumber = model.PhoneNumber,
                Password = model.Password
            });

            var result = 0;
            result = _db.SaveChanges();
            if (result > 0)
            {
                return ApiResult.SUCCESS;
            }
            return ApiResult.REGISTER_FAILED_DB_NOCHANGE;
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public object Login([FromBody] UserLoginRM model)
        {
            var user = _db.Users.FirstOrDefault(u => u.PhoneNumber == model.PhoneNumber && u.Password == model.Password);
            if (user == null)
            {
                return ApiResult.LOGIN_FAILED_USER_NOTFOUND;
            }

            var token = _jwtService.CreateToken(user.UserId);
            return ApiResult.Success(token);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns>查询用户各订单状态数量，用户头像，用户昵称（如果没有设置昵称用手机号码代替）</returns>
        [HttpGet]
        [Authorize]
        public object GetUserInfo()
        {
            var userId = _jwtService.GetUserId(HttpContext);
            // 使用DTO: UserInfo
            var userInfo = _db.Users
                .Where(u => u.UserId == userId)
                .Select(u => new Models.DTO.UserInfo
                {
                    UserId = u.UserId,
                    PhoneNumber = u.PhoneNumber,
                    NickName = u.NickName ?? u.PhoneNumber,
                    Avatar = u.Avatar,
                    OrderCount = _db.Orders.Count(o => o.UserId == userId)
                })
                .FirstOrDefault();

            if (userInfo == null)
            {
                return ApiResult.USER_NOT_FOUND;
            }

            return ApiResult.Success(userInfo);
        }

        /// <summary>
        /// 修改用户信息(头像, 昵称)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public object UpdateUserInfo([FromBody] UserUpdateInfoRM model)
        {
            var userId = _jwtService.GetUserId(HttpContext);
            var user = _db.Users.FirstOrDefault(u => u.UserId == userId);
            if (user == null)
            {
                return ApiResult.USER_NOT_FOUND;
            }

            user.NickName = model.NickName;
            user.Avatar = model.Avatar;
            var result = _db.SaveChanges();
            if (result > 0)
            {
                return ApiResult.SUCCESS;
            }
            return ApiResult.UPDATE_FAILED_DB_NOCHANGE;
        }
    }
}
